import { useEffect, useRef } from "react";
import { Mesh, Object3D } from "three";
import { easing } from "maath";

export default function useUpdateMaterial(
  ref: React.RefObject<Object3D>,
  active: boolean
) {
  const cachedMaterials = useRef(new Map()); // 用于缓存每个 Mesh 的 material

  useEffect(() => {
    if (!ref.current) return;
    ref.current.traverse((obj) => {
      if (obj instanceof Mesh && obj.material) {
        if (!cachedMaterials.current.has(obj)) {
          cachedMaterials.current.set(obj, obj.material);
        }
      }
    });
  }, []);

  useEffect(() => {
    if (!ref.current) return;
    startAni();
  }, [active]);

  function startAni() {
    let start: number | null = null;
    const duration = 300; // 动画持续时间 (毫秒)
    let last = Date.now();
    function animate(time: number) {
      if (!start) start = time;
      const elapsed = time - start;
      // 计算 delta
      const currentTime = Date.now();
      const delta = (currentTime - last) / 1000; // 转换为秒
      last = currentTime; // 更新last为当前时间

      ref.current?.traverse((obj) => {
        if (obj instanceof Mesh && obj.material) {
          const material = cachedMaterials.current.get(obj);
          if (material) {
            easing.damp(material, "grayscale", active ? 0 : 0.5, 0.15, delta);
            easing.dampC(
              material.color,
              active ? "white" : "#bbb",
              active ? 0.3 : 0.15,
              delta
            );
          }
        }
      });
      if (elapsed < duration) {
        requestAnimationFrame(animate); // 如果动画未结束，继续请求下一帧
      }
    }
    requestAnimationFrame(animate);
  }
}
